package com.sky.aspect;

import com.sky.annotation.Autofill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.Autofill)")
    public void autoFillPointCut()
    {
    }
    @SneakyThrows
    @Before("autoFillPointCut()")
    public void beforeAutoFill(JoinPoint joinPoint) throws Exception {
        log.info("开始进入公共字段的填充");
        //获取当前被拦截的方法上数据库操作
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名对象
        Autofill autofill = signature.getMethod().getAnnotation(Autofill.class);//获得方法上的注解对象
        OperationType operationType = autofill.value();//获得操作类型

        //获取参数 实体对象
        Object[] args = joinPoint.getArgs();
        if(args.length == 0||args[0]==null)
        {
            return;
        }
        Object entity = args[0];
        //准备赋值数据
        LocalDateTime localDateTime = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        //根据不同操作类型
        if(operationType==OperationType.INSERT){
            try {
                Method seCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME,LocalDateTime.class);
                Method seUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
                seCreateTime.invoke(entity,localDateTime);
                seUpdateTime.invoke(entity,localDateTime);
                setCreateUser.invoke(entity,currentId);
                setUpdateUser.invoke(entity,currentId);
            } catch ( Exception exception) {
                throw exception;
            }


        }
        else if(operationType==OperationType.UPDATE){}
        try {
            Method seUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
            Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER,Long.class);
            seUpdateTime.invoke(entity,localDateTime);
            setUpdateUser.invoke(entity,currentId);
        } catch (Exception exception) {
            throw exception;
        }
    }
}
